package org.maven.dependencybrowser.config;
/**********************************************************************
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

Contributors:

**********************************************************************/
import org.maven.dependencybrowser.implementations.local.LocalDiskRepository;
import org.maven.dependencybrowser.implementations.local.LocalDiskWorkspace;

import javax.swing.*;
import java.awt.*;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Properties;

public class Config
{

    public static final String ROLE = "org.maven.dependencybrowser.config.Config";

    private static final String KEY_WORKSPACE = LocalDiskWorkspace.KEY_WORKSPACE_PATH;
    private static final String KEY_REPOSITORY = LocalDiskRepository.KEY_LOCAL_REPO_PATH;
    private static final String CONFIG_FILE = ".dependency-browser";

    private JDialog dialog;

    private JTextField workspace;
    private JTextField repository;

    private JButton okButton;
    private JButton cancelButton;

    public Properties configure()
    {
        dialog = new JDialog(new JFrame(), true);
        dialog.setTitle("Configure Maven Dependency Browser");
        dialog.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        dialog.getContentPane().setLayout(new BoxLayout(dialog.getContentPane(), BoxLayout.PAGE_AXIS));

        final Properties properties = getProperties();
        workspace = new JTextField(properties.getProperty(KEY_WORKSPACE));
        repository = new JTextField(properties.getProperty(KEY_REPOSITORY));

        JPanel buttons = new JPanel();
        buttons.setLayout(new FlowLayout(FlowLayout.RIGHT, 5, 5));
        okButton = new JButton("OK");
        okButton.setPreferredSize(new Dimension(75, 20));
        okButton.addMouseListener(new MouseAdapter()
        {

            public void mouseClicked(MouseEvent e)
            {
                properties.setProperty(KEY_WORKSPACE, workspace.getText());
                properties.setProperty(KEY_REPOSITORY, repository.getText());
                saveProperties(properties);
                dialog.dispose();
            }

        });
        buttons.add(okButton);
        cancelButton = new JButton("Cancel");
        cancelButton.setPreferredSize(new Dimension(75, 20));
        cancelButton.addMouseListener(new MouseAdapter()
        {

            public void mouseClicked(MouseEvent e)
            {
                dialog.dispose();
            }

        });
        buttons.add(cancelButton);
        validate();

        dialog.getContentPane().add(createPanel("Workspace: ", workspace));
        dialog.getContentPane().add(createPanel("Repository: ", repository));
        dialog.getContentPane().add(buttons);
        dialog.pack();
        dialog.setVisible(true);
        return properties;
    }

    private void validate()
    {
        if (workspace.getText() == null || workspace.getText().length() == 0)
        {
            okButton.setEnabled(false);
            return;
        }
        if (workspace.getText() == null || repository.getText().length() == 0)
        {
            okButton.setEnabled(false);
            return;
        }
        okButton.setEnabled(true);
    }

    private JPanel createPanel(String label, final JTextField text)
    {
        JPanel panel = new JPanel();
        panel.setLayout(new FlowLayout(FlowLayout.LEFT, 5, 5));
        panel.add(new JLabel(label));
        text.setEditable(false);
        text.setPreferredSize(new Dimension(300, 20));
        panel.add(text);
        JButton button = new JButton("...");
        button.setPreferredSize(new Dimension(25, 20));
        panel.add(button);
        button.addMouseListener(new MouseAdapter()
        {

            public void mouseClicked(MouseEvent e)
            {
                File dir = selectDirectory();
                if (dir != null)
                {
                    text.setText(dir.getPath());
                    validate();
                }
            }

        });
        return panel;
    }

    private File selectDirectory()
    {
        JFileChooser fc = new JFileChooser()
        {

            public void updateUI()
            {
                // workaround for bug http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6317789
                putClientProperty("FileChooser.useShellFolder", Boolean.FALSE);
                super.updateUI();
            }
        };
        fc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
        int returnVal = fc.showOpenDialog(dialog);
        if (returnVal == JFileChooser.APPROVE_OPTION)
        {
            File file = fc.getSelectedFile();
            if (file.isDirectory())
            {
                return file;
            }
        }
        return null;
    }

    private Properties getProperties()
    {
        Properties properties = new Properties();
        File propertiesFile = getPropertiesFile();
        if (propertiesFile != null && propertiesFile.exists())
        {
            try
            {
                properties.load(new FileInputStream(propertiesFile));
            }
            catch (IOException e)
            {
                System.err.println("Could not open properties file: " + propertiesFile.getPath());
                e.printStackTrace(System.err);
            }
        }
        return properties;
    }

    private File getPropertiesFile()
    {
        return new File(System.getProperty("user.home"), CONFIG_FILE);
    }

    private void saveProperties(Properties properties)
    {
        File propertiesFile = getPropertiesFile();
        try
        {
            properties.store(new FileOutputStream(propertiesFile), "");
        }
        catch (IOException e)
        {
            System.err.println("Could not save properties file: " + propertiesFile.getPath());
            e.printStackTrace(System.err);
        }
    }

}
